<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useBlogStore } from '@/stores/useBlogStore'
import type { Article, Tag, Timestamp } from '@/types/blog.types'
import {
  DropdownMenuRoot,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuPortal,
} from 'reka-ui'

defineOptions({
  name: 'BlogPage',
})

const router = useRouter()
const blogStore = useBlogStore()
const { articles, loading } = storeToRefs(blogStore)

// 搜索和筛选状态
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedTag = ref('')
const sortBy = ref<'latest' | 'popular' | 'views' | 'likes'>('latest')
const showType = ref<'all' | 'pinned' | 'favorites'>('all')

// 排序选项类型定义
interface SortOption {
  value: 'latest' | 'popular' | 'views' | 'likes'
  label: string
  icon: string
}

// 显示类型选项类型定义
interface ShowTypeOption {
  value: 'all' | 'pinned' | 'favorites'
  label: string
  icon: string
  count: number
}

// 排序选项
const sortOptions: SortOption[] = [
  { value: 'latest', label: '最新发布', icon: '🕒' },
  { value: 'popular', label: '最热文章', icon: '🔥' },
  { value: 'views', label: '浏览最多', icon: '👁️' },
  { value: 'likes', label: '点赞最多', icon: '❤️' },
]

// 显示类型选项
const showTypeOptions = ref<ShowTypeOption[]>([
  { value: 'all', label: '全部文章', icon: '📝', count: 0 },
  { value: 'pinned', label: '固定文章', icon: '📌', count: 0 },
  { value: 'favorites', label: '收藏文章', icon: '⭐', count: 0 },
])

// 计算过滤后的文章
const filteredArticles = computed(() => {
  let result = (articles.value || []).filter((article: Article) => article.status === 'published')

  // 显示类型过滤
  if (showType.value === 'pinned') {
    result = result.filter((article: Article) => article.featured)
  } else if (showType.value === 'favorites') {
    result = result.filter((article: Article) => article.featured)
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter((article: Article) => {
      const authorName =
        typeof article.author === 'string' ? article.author : article.author?.name || ''

      return (
        article.title.toLowerCase().includes(query) ||
        (article.excerpt && article.excerpt.toLowerCase().includes(query)) ||
        authorName.toLowerCase().includes(query)
      )
    })
  }

  // 分类过滤
  if (selectedCategory.value) {
    result = result.filter((article: Article) => article.category.slug === selectedCategory.value)
  }

  // 标签过滤
  if (selectedTag.value) {
    result = result.filter((article: Article) =>
      article.tags.some((tag: Tag) => tag.slug === selectedTag.value),
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'latest':
      return result.sort((a: Article, b: Article) => {
        const dateA = new Date(a.publishDate || a.createdAt).getTime()
        const dateB = new Date(b.publishDate || b.createdAt).getTime()
        return dateB - dateA
      })
    case 'popular':
      return result.sort((a: Article, b: Article) => (b.likeCount || 0) - (a.likeCount || 0))
    case 'views':
      return result.sort((a: Article, b: Article) => (b.viewCount || 0) - (a.viewCount || 0))
    case 'likes':
      return result.sort((a: Article, b: Article) => (b.likeCount || 0) - (a.likeCount || 0))
    default:
      return result
  }
})

// 更新显示类型计数
const updateShowTypeCounts = () => {
  const allArticles = (articles.value || []).filter(
    (article: Article) => article.status === 'published',
  )
  showTypeOptions.value[0].count = allArticles.length
  showTypeOptions.value[1].count = allArticles.filter((article: Article) => article.featured).length
  showTypeOptions.value[2].count = allArticles.filter((article: Article) => article.featured).length
}

// 监听文章变化更新计数
watch(articles, updateShowTypeCounts, { immediate: true })

// 初始化数据
onMounted(async () => {
  try {
    await blogStore.initializeData()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})

/**
 * 简单的日期格式化
 */
const formatDate = (date: Timestamp): string => {
  return new Date(date).toLocaleDateString('zh-CN')
}

/**
 * 清除筛选
 */
const clearFilters = (): void => {
  searchQuery.value = ''
  selectedCategory.value = ''
  selectedTag.value = ''
  sortBy.value = 'latest'
  showType.value = 'all'
}

/**
 * 分类点击处理
 */
const handleCategoryClick = (categorySlug: string): void => {
  selectedCategory.value = categorySlug
  selectedTag.value = ''
}

/**
 * 标签点击处理
 */
const handleTagClick = (tagSlug: string): void => {
  selectedTag.value = tagSlug
  selectedCategory.value = ''
}

/**
 * 文章点击处理
 */
const handleArticleClick = (article: Article): void => {
  router.push(`/article/${article.id}`)
}

/**
 * 获取作者名称
 */
const getAuthorName = (author: Article['author']): string => {
  return typeof author === 'string' ? author : author?.name || '未知作者'
}

/**
 * 根据value查找排序选项
 */
const findSortOption = (value: string): SortOption | undefined => {
  return sortOptions.find((s: SortOption) => s.value === value)
}

/**
 * 处理排序选择
 */
const handleSortChange = (value: 'latest' | 'popular' | 'views' | 'likes'): void => {
  sortBy.value = value
}
</script>

<template>
  <div class="blog-page min-h-screen bg-base-100">
    <!-- Page Header -->
    <header class="bg-base-200 shadow-sm">
      <div class="container mx-auto px-4 py-6 sm:py-12">
        <h1
          class="text-3xl sm:text-4xl md:text-5xl font-bold text-center mb-4 sm:mb-6 text-base-content"
        >
          📝 博客文章
        </h1>
        <p
          class="text-base sm:text-lg md:text-xl text-center text-base-content/70 max-w-2xl mx-auto px-4"
        >
          探索技术世界，分享开发经验，记录学习成长的点点滴滴
        </p>
      </div>
    </header>

    <div class="container mx-auto px-4 py-4 sm:py-8">
      <!-- 移动端筛选按钮 -->
      <div class="lg:hidden mb-4">
        <label for="sidebar-drawer" class="btn btn-primary btn-block gap-2 drawer-button">
          <i class="ph ph-funnel text-lg"></i>
          筛选和排序
        </label>
      </div>

      <div class="drawer lg:drawer-open">
        <input id="sidebar-drawer" type="checkbox" class="drawer-toggle" />

        <div class="drawer-content">
          <div class="lg:ml-8">
            <!-- 当前筛选状态 -->
            <div
              v-if="searchQuery || selectedCategory || selectedTag"
              class="card bg-base-200 shadow-lg mb-6 border border-base-300/50"
            >
              <div class="card-body p-4">
                <h3 class="card-title text-base sm:text-lg mb-3 flex items-center gap-2">
                  <span>🎯</span>
                  <span>当前筛选</span>
                </h3>
                <div class="flex flex-wrap gap-2">
                  <div v-if="searchQuery" class="badge badge-primary gap-2">
                    🔍 搜索: {{ searchQuery }}
                    <button
                      @click="searchQuery = ''"
                      class="btn btn-ghost btn-xs hover:bg-primary-content/20"
                    >
                      ×
                    </button>
                  </div>
                  <div v-if="selectedCategory" class="badge badge-secondary gap-2">
                    📂 分类:
                    <button
                      @click="selectedCategory = ''"
                      class="btn btn-ghost btn-xs hover:bg-secondary-content/20"
                    >
                      ×
                    </button>
                  </div>
                  <div v-if="selectedTag" class="badge badge-accent gap-2">
                    🏷️ 标签:
                    <button
                      @click="selectedTag = ''"
                      class="btn btn-ghost btn-xs hover:bg-accent-content/20"
                    >
                      ×
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 文章统计和排序 -->
            <div
              class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-3"
            >
              <div class="text-base-content/70">
                共找到
                <span class="font-semibold text-primary">{{ filteredArticles.length }}</span> 篇文章
              </div>

              <!-- 排序下拉选择器 -->
              <DropdownMenuRoot>
                <DropdownMenuTrigger
                  class="btn btn-outline btn-sm gap-2 inline-flex items-center justify-center w-full sm:w-auto"
                >
                  <span>{{ findSortOption(sortBy)?.icon }}</span>
                  <span>{{ findSortOption(sortBy)?.label }}</span>
                  <span>🔽</span>
                </DropdownMenuTrigger>

                <DropdownMenuPortal>
                  <DropdownMenuContent
                    class="bg-base-100 rounded-box shadow-xl border border-base-300 p-2 min-w-52 z-50"
                    :side="'bottom'"
                    :align="'end'"
                    :sideOffset="5"
                  >
                    <DropdownMenuItem
                      v-for="option in sortOptions"
                      :key="option.value"
                      @select="handleSortChange(option.value)"
                      class="flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer hover:bg-base-200 transition-colors"
                      :class="{
                        'bg-primary text-primary-content': sortBy === option.value,
                      }"
                    >
                      <span>{{ option.icon }}</span>
                      <span>{{ option.label }}</span>
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenuPortal>
              </DropdownMenuRoot>
            </div>

            <!-- Loading State -->
            <div v-if="loading" class="flex justify-center items-center py-20">
              <div class="loading loading-spinner loading-lg text-primary"></div>
              <span class="ml-4 text-base sm:text-lg text-base-content/70">加载中...</span>
            </div>

            <!-- Empty State -->
            <div v-else-if="filteredArticles.length === 0" class="text-center py-20 px-4">
              <div class="text-5xl sm:text-6xl mb-4">📝</div>
              <h3 class="text-xl sm:text-2xl font-bold text-base-content mb-2">暂无文章</h3>
              <p class="text-base-content/70 mb-6 text-sm sm:text-base">
                {{
                  searchQuery || selectedCategory || selectedTag
                    ? '没有找到符合条件的文章'
                    : '还没有发布任何文章'
                }}
              </p>
              <button
                v-if="searchQuery || selectedCategory || selectedTag"
                @click="clearFilters"
                class="btn btn-primary"
              >
                清除筛选条件
              </button>
            </div>

            <!-- Articles List -->
            <div v-else class="space-y-4 sm:space-y-6">
              <article
                v-for="(article, index) in filteredArticles"
                :key="article.id"
                @click="handleArticleClick(article)"
                class="card bg-base-200 shadow-lg hover:shadow-2xl cursor-pointer transition-all duration-500 hover:-translate-y-2 group overflow-hidden"
                :style="{ animationDelay: `${index * 100}ms` }"
              >
                <div class="card-body p-0">
                  <div class="flex flex-col md:flex-row">
                    <!-- Article Cover -->
                    <div class="md:w-1/3 aspect-video md:aspect-square overflow-hidden relative">
                      <img
                        :src="
                          article.coverImage || `https://picsum.photos/400/300?random=${article.id}`
                        "
                        :alt="article.title"
                        class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 ease-out"
                      />
                      <div
                        class="absolute inset-0 bg-gradient-to-t from-black/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                      ></div>
                      <div
                        class="absolute top-4 right-4 opacity-0 group-hover:opacity-100 transition-all duration-300 transform translate-x-2 group-hover:translate-x-0"
                      >
                        <div class="bg-white/90 backdrop-blur-sm rounded-full p-2">
                          <svg
                            class="w-4 h-4 text-primary"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              stroke-width="2"
                              d="M13 7l5 5m0 0l-5 5m5-5H6"
                            ></path>
                          </svg>
                        </div>
                      </div>
                    </div>

                    <!-- Article Content -->
                    <div class="md:w-2/3 p-4 sm:p-6">
                      <!-- 固定和收藏标识 -->
                      <div class="flex items-center gap-2 mb-3">
                        <div
                          v-if="article.featured"
                          class="badge badge-warning gap-1 animate-pulse-slow text-xs sm:text-sm"
                        >
                          📌 精选
                        </div>
                      </div>

                      <!-- Meta Info -->
                      <div
                        class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 gap-2"
                      >
                        <div class="flex items-center gap-3">
                          <div
                            class="badge badge-sm font-medium text-xs"
                            :style="{
                              backgroundColor: (article.category.color || '#6b7280') + '20',
                              color: article.category.color || '#6b7280',
                              borderColor: (article.category.color || '#6b7280') + '40',
                            }"
                          >
                            {{ article.category.name }}
                          </div>
                          <time class="text-xs sm:text-sm text-base-content/60">{{
                            formatDate(article.publishDate || article.createdAt)
                          }}</time>
                        </div>
                        <div class="text-xs sm:text-sm text-base-content/60">
                          {{ getAuthorName(article.author) }}
                        </div>
                      </div>

                      <!-- Title -->
                      <h2
                        class="text-lg sm:text-xl font-bold text-base-content mb-3 group-hover:text-primary transition-all duration-300 line-clamp-2 group-hover:scale-105 transform origin-left"
                      >
                        {{ article.title }}
                      </h2>

                      <!-- Excerpt -->
                      <p class="text-sm sm:text-base text-base-content/70 mb-4 line-clamp-2">
                        {{ article.excerpt }}
                      </p>

                      <!-- Tags -->
                      <div class="flex flex-wrap gap-2 mb-4">
                        <button
                          v-for="tag in (article.tags || []).slice(0, 4)"
                          :key="tag.id"
                          @click.stop="handleTagClick(tag.slug)"
                          class="badge badge-outline badge-sm hover:badge-primary transition-all duration-300 hover:scale-110 hover:shadow-md transform text-xs"
                        >
                          {{ tag.name }}
                        </button>
                      </div>

                      <!-- Footer Stats -->
                      <div
                        class="flex items-center justify-between text-xs sm:text-sm text-base-content/60"
                      >
                        <div class="flex items-center gap-3 sm:gap-4">
                          <span class="flex items-center gap-1">
                            <svg
                              class="w-3 h-3 sm:w-4 sm:h-4"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                              />
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                              />
                            </svg>
                            {{ article.viewCount || 0 }}
                          </span>
                          <span class="flex items-center gap-1">
                            <svg
                              class="w-3 h-3 sm:w-4 sm:h-4"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
                              />
                            </svg>
                            {{ article.likeCount || 0 }}
                          </span>
                          <span class="flex items-center gap-1">
                            <svg
                              class="w-3 h-3 sm:w-4 sm:h-4"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
                              />
                            </svg>
                            {{ article.readTime }} 分钟
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </article>
            </div>
          </div>
        </div>

        <!-- 侧边栏 (抽屉式) -->
        <div class="drawer-side z-50">
          <label for="sidebar-drawer" class="drawer-overlay"></label>
          <aside class="bg-base-100 min-h-screen w-80 p-4 space-y-6">
            <!-- 关闭按钮 (移动端) -->
            <div class="lg:hidden flex justify-between items-center mb-4">
              <h2 class="text-xl font-bold text-base-content">筛选选项</h2>
              <label for="sidebar-drawer" class="btn btn-ghost btn-sm btn-circle">
                <i class="ph ph-x text-xl"></i>
              </label>
            </div>

            <!-- 文章类型 -->
            <div
              class="card bg-base-200 shadow-md border border-base-300 hover:shadow-lg transition-all duration-300"
            >
              <div class="card-body p-4">
                <h3 class="text-base font-semibold text-base-content mb-3 flex items-center gap-2">
                  <span>📋</span>
                  <span>文章类型</span>
                </h3>
                <div class="space-y-2">
                  <button
                    v-for="option in showTypeOptions"
                    :key="option.value"
                    @click="showType = option.value"
                    class="w-full flex items-center justify-between p-2 sm:p-3 rounded-lg transition-all duration-200 hover:bg-base-300 text-sm"
                    :class="{
                      'bg-primary text-primary-content shadow-sm': showType === option.value,
                      'bg-base-100 text-base-content hover:bg-base-300': showType !== option.value,
                    }"
                  >
                    <div class="flex items-center gap-2">
                      <span class="text-sm">{{ option.icon }}</span>
                      <span class="font-medium">{{ option.label }}</span>
                    </div>
                    <span
                      class="text-xs px-2 py-1 rounded-full font-medium"
                      :class="
                        showType === option.value
                          ? 'bg-primary-content/20 text-primary-content'
                          : 'bg-base-300 text-base-content'
                      "
                    >
                      {{ option.count }}
                    </span>
                  </button>
                </div>
              </div>
            </div>

            <!-- 分类 -->
            <div
              class="card bg-base-200 shadow-md border border-base-300 hover:shadow-lg transition-all duration-300"
            >
              <div class="card-body p-4">
                <h3 class="text-base font-semibold text-base-content mb-3 flex items-center gap-2">
                  <span>📂</span>
                  <span>文章分类</span>
                </h3>
                <div class="max-h-60 overflow-y-auto custom-scrollbar">
                  <div class="space-y-2">
                    <button
                      @click="handleCategoryClick('')"
                      class="w-full flex items-center justify-between p-2 sm:p-3 rounded-lg transition-all duration-200 hover:bg-base-300 text-sm"
                      :class="{
                        'bg-primary text-primary-content shadow-sm': selectedCategory === '',
                        'bg-base-100 text-base-content hover:bg-base-300': selectedCategory !== '',
                      }"
                    >
                      <div class="flex items-center gap-2">
                        <span class="text-sm">📝</span>
                        <span class="font-medium">全部分类</span>
                      </div>
                      <span
                        class="text-xs px-2 py-1 rounded-full font-medium"
                        :class="
                          selectedCategory === ''
                            ? 'bg-primary-content/20 text-primary-content'
                            : 'bg-base-300 text-base-content'
                        "
                      >
                        {{ (articles || []).length }}
                      </span>
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 清除筛选 -->
            <div
              v-if="
                searchQuery ||
                selectedCategory ||
                selectedTag ||
                sortBy !== 'latest' ||
                showType !== 'all'
              "
              class="card bg-base-200 shadow-md border border-base-300 hover:shadow-lg transition-all duration-300"
            >
              <div class="card-body p-4">
                <button
                  @click="clearFilters"
                  class="w-full flex items-center justify-center gap-2 px-4 py-2 sm:py-3 bg-error text-error-content rounded-lg font-medium transition-all duration-200 hover:bg-error-focus hover:shadow-md text-sm"
                >
                  <span>🗑️</span>
                  <span>清除所有筛选</span>
                </button>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-clamp: 2;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-clamp: 3;
}

/* 文章卡片进入动画 */
article {
  animation: slideInUp 0.6s ease-out forwards;
  opacity: 0;
  transform: translateY(30px);
}

@keyframes slideInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 悬停效果增强 */
.group:hover .group-hover\:scale-105 {
  transform: scale(1.05);
}

/* 图片悬停效果 */
.group:hover img {
  filter: brightness(1.1) contrast(1.05);
}

/* 标签悬停效果 */
.badge:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 卡片阴影效果 */
.card {
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.card:hover {
  box-shadow:
    0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 自定义滚动条样式 */
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: hsl(var(--p)) transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 4px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: hsl(var(--p) / 0.5);
  border-radius: 2px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: hsl(var(--p) / 0.8);
}

/* 侧边栏按钮样式优化 */
.sidebar-button {
  position: relative;
  overflow: hidden;
}

.sidebar-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transition: left 0.5s;
}

.sidebar-button:hover::before {
  left: 100%;
}
</style>
